# -*-coding:utf-8-*-

from protocol import *
from base import *
import logConfig as log

FN_KEY='AZ-FN-CODEC-KEY'

# ********************
# HTTP请求接口
# 参数部分的封装
# ********************
# 获取HTTP中的Token,并组装请求数据
def getToken(_body, _key):
    if (not _body and not _key):
        log.debug('========== getToken 参数错误  ==========')
        return
    arr = []
    tmp = ''
    if isinstance(_body, dict):
        for key in _body:
            arr.append(key)
        arr.sort()

        for i in range(len(arr)):
            tmp += str(_body[arr[i]])
        tmp += _key
        _body['token'] = md5(tmp.upper())
        return _body
    else:
        log.debug('========== getToken 参数错误  ==========')

def getGroupQueyToken(_body,_key):
    if (not _body and not _key):
        log.debug('========== getToken 参数错误  ==========')
        return
    arr = []
    tmp = ''
    if isinstance(_body, dict):
        for key in _body:
            arr.append(key)
        arr.sort()

        for i in range(len(arr)):
            tmp += str(_body[arr[i]])
        tmp += _key
        _body['token'] = md5(tmp.upper())
        return _body
    else:
        log.debug('========== getToken 参数错误  ==========')

# ********************
# HTTP请求接口
# 参数部分的封装
# ********************

# 终端软件查询更新接口
def getSoftwareQuery(currentversion, imei, modeCode):
    #baseData = {'currentversion':currentversion,'imei':imei,'modeCode':modeCode,'userType':userType,'timestamp':str(getTimestamp())}
    baseData = {'currentversion':currentversion,'imei':imei,'modeCode':modeCode,'timestamp':str(getTimestamp())}
    return getToken(baseData, FN_KEY)

# 登录接口：{'address':'/app/login.do','method':'post'}
def getLoginMsg(userCode, password, userType):
    baseData = {'userCode':userCode,'password':md5(password),'timestamp':str(getTimestamp()),'userType':str(userType),'deviceId':''}
    return getToken(baseData, FN_KEY)

# 群组信息查询接口接口
def getGroupQueryMsg(userid,companyid,userType,groupMd5,userToken):
    baseData = {'userid':userid,'companyid':companyid,'userType':userType,'timestamp':str(getTimestamp()),'groupMd5':'','key':userToken}
    #baseData = {'userid':userid,'companyid':companyid,'userType':userType,'timestamp':str(getTimestamp()),'groupMd5':''}
    return getToken(baseData, FN_KEY)

# 群组成员查询接口
def getGroupMemberQueryMsg(userid, groupid, companyid, userType, userToken):
    baseData = {'userid':userid,'groupid':groupid,'companyid':companyid,'userType':userType,'timestamp':str(getTimestamp()),'key':userToken}
    return getToken(baseData, FN_KEY)

# 获取所有群组与成员信息：{'address':'/app/login.do','method':'get/post'}
def getGroupMemberLocationsQueryMsg(userid, userType, companyid, userToken):
    baseData = {'userid':userid,'userType':userType,'companyid':companyid,'key':userToken,'timestamp':str(getTimestamp())}
    return getToken(baseData, FN_KEY)

# 创建临时组：{'address':'/app/createTemporaryGroup.do','method':'get/post'}
def getCreateTemporaryGroupMsg(uid, userType, cmpid, userToken, groupType, memberIds):
    baseData = {'userid':uid,'userType':userType,'companyid':cmpid,'key':userToken,'groupType':groupType,'memberIds':memberIds,'timestamp':str(getTimestamp())}
    return getToken(baseData, FN_KEY)

# 创建广播临时组createTemporaryGroup4Broadcast
def getCreateTemporaryGroup4Broadcast(uid, userType, cmpid, userToken, groupType, groupIds):
    baseData = {'userid':uid,'userType':userType,'companyid':cmpid,'key':userToken,'groupType':groupType,'groupIds':groupIds,'timestamp':str(getTimestamp())}
    return getToken(baseData, FN_KEY)

# ********************
# TCP交互接口
# 请求数据部分的封装
# ********************
# TCP信令模块采用WEBSOCKET协议传输信息，消息为JSON文本格式
# cmd：信令ID
# v：协议版本号，目前为1
# msgid：时间戳，精确到毫秒
# rsp：0-不需要回复 1-需要回复
# body：传输参数内容，JSON格式
def assemblyTCPData(cmd, version, rsp, body):
    msg = {'cmd': cmd,'v': version,'msgid': str(getTimestamp()),'rsp': rsp,'body': body}
    return str(msg)

# ********************
# TCP交互接口
# 参数部分的封装
# ********************
# TCP接入接口参数的获取:1——>8001
def getAccessMsg(cmpid, uid, pwd, type, key):
    ts = str(getTimestamp())
    tmp = str(cmpid) + str(pwd) + ts + str(type) + str(uid) + key
    return {
        'cmpid':cmpid,
        'ts':ts,
        'type':type,
        'uid':uid,
        'pwd':md5(tmp.upper())
    }

# TCP心跳接口参数的获取:2——>8002
def getHeartBeatMsg(cmpid, uid, token):
    if cmpid and uid and token:
        return {
            'cmpid':cmpid,
            'uid':uid,
            'token':str(token)
        }
    else:
        log.info(u"参数有误!"+"cmpid: "+str(cmpid)+" uid: "+str(uid)+" token: "+str(token))

# 进入语音频道（组）:3——>8003
def getInVoiceChannelMsg(cmpid, uid, gid, type):
    return {
        'cmpid':cmpid,
        'uid':uid,
        'gid':gid,
        'type':type
    }

# 退出语音频道（组）:4——>8004
def getOutVoiceChannelMsg(cmpid, uid):
    return {
        'cmpid':cmpid,
        'uid':uid
    }

# 音视频单呼: 7——>8007
def getVideoSingleCallMsg(cmpid, eruid, eduid, gid):
    return {
        'cmpid':cmpid,
        'eruid':eruid,
        'eduid':eduid,
        'gid':gid
    }

# 音视频单呼: 8——>8008（server）
def getVideoSingleCallMsg_server(stat, err, gid, uid):
    return {
        'stat':stat,
        'err':err,
        'gid':gid,
        'uid':uid
    }

# 音视频组呼：9——>8009
def getVideoGroupCallMsg(cmpid, eruid, gid):
    return {
        'cmpid':cmpid,
        'eruid':eruid,
        'gid':gid
    }

# 音视频组呼：10——>8010（server）
def get_videoGroupCallMsg(cmpid, gid, ername, eduid, ch, cid, sid):
    return {
        'cmpid':cmpid,
        'gid':gid,
        'ername':ername,
        'eduid':eduid,
        'ch':ch,
        'cid':cid,
        'sid':sid
    }

# 呼叫结束：11——>8011
def getVideoCallHangUpMsg(cid, sid, gid, uid):
    return {
        'cid':cid,
        'sid':sid,
        'gid':gid,
        'uid':uid
    }

# 呼叫结束：12——>8012（server）
def getVideoCallHangUpMsg_server(stat, err, ch, cid, sid, gid):
    return {
        'stat':stat,
        'err':err,
        'ch':ch,
        'cid':cid,
        'sid':sid,
        'gid':gid
    }

# LBS位置推送：14
def getPushLbsMsg(cmpid, uid, lat, lng):
    return {
        'cmpid':cmpid,
        'uid':uid,
        'lat':lat,
        'lng':lng
    }

# LBS位置推送：15（server）
def get_pushLbsMsg(cmpid, uid, lat, lng, ceratetime):
    return {
        'cmpid':cmpid,
        'uid':uid,
        'lat':lat,
        'lng':lng,
        'ceratetime':ceratetime
    }

# 广播：16——>8016
def getBoardcastMsg(cmpid, gid, uid):
    return {
        'cmpid':cmpid,
        'gid':gid,
        'uid':uid
    }

# 广播：17——>8017（server）
def getBoardcastMsg_sever(stat, err, gid, uid):
    return {
        'stat': stat,
        'err': err,
        'gid': gid,
        'uid':uid
    }

# 广播结束：18——>8018
def getBoardcastHangUpMsg(cid, sid, gid, uid):
    return {
        'cid':cid,
        'sid':sid,
        'gid':gid,
        'uid':uid
    }

# 广播结束：19——>8019（server）
def geBoardcastHangUpMsg_server(stat, err, gid, uid):
    return {
        'stat':stat,
        'err':err,
        'gid':gid,
        'uid':uid
    }

# 临时组对讲：20——>8020
def getTemporaryTalkMsg(cmpid, eruid, gid):
    return {
        'cmpid':cmpid,
        'eruid':eruid,
        'gid':gid
    }

# 临时组对讲：21——>8021（server）
def getTemporaryTalkMsg_server(stat, err, gid, uid):
    return {
        'stat':stat,
        'err':err,
        'gid':gid,
        'uid':uid
    }

# 临时组对讲结束：22——>8022
def getTemporaryTalkHangUpMsg(cid, sid, gid, uid):
    return {
        'cid':cid,
        'sid':sid,
        'gid':gid,
        'uid':uid
    }

# 临时组对讲结束：23——>8023
def getTemporaryTalkHangUpMsg_server(stat, err, gid):
    return {
        'stat':stat,
        'err':err,
        'gid':gid
    }
    pass

# 单呼结束：5——>8005
def getVideoSingleCallHangUpMsg(cid, sid, gid, uid):
    return {
        'cid':cid,
        'sid':sid,
        'gid':gid,
        'uid':uid
    }

# 单呼结束：5——>8006（server）
def get_videoSingleCallHangUpMsg(cid, sid, gid):
    return {
        'cid':cid,
        'sid':sid,
        'gid':gid
    }

# 结束所有回话状态：24
def getEndAllSession(cid, sid, stat, gid, uid, type):
    return {
        'cid':cid,
        'sid':sid,
        'stat':stat,
        'gid':gid,
        'uid':uid,
        'type':type
    }

# ********************
# TCP接收数据的处理
# ********************
# TCP接入数据：8001
def fnTcp_accessHandler(cpu, msg, uid=None):
    try:
        if msg["err"] == 0:
            if uid == None:
                cpu["data"]._const["WS"]["TOKEN"] = msg["token"]
            else:
                cpu[uid]["token"] = msg["token"]
            #thread_heartbeat_create(websocket, cmpid, uid, cpu[uid]["token"])
        else:
            log.info("Click to exit the system!")
    except Exception,e:
        log.error(str(e))

# TCP心跳：8002
def fnTcp_heartBeatHandler():
    #log.info("WS   Send:  HeartBeat...")
    pass

# 进入语音频道（组）：8003
def fnTcp_inChannelHandler(cpu,msg):
    try:
        if msg["err"] == 0:
            cpu["data"]._const["WS"]["cid"] = msg["cid"]
            cpu["data"]._const["WS"]["sid"] = msg["sid"]
            cpu["data"]._const["WS"]["aip"] = msg["aip"]
            cpu["data"]._const["WS"]["aport"] = msg["aport"]
            cpu["data"]._const["WS"]["stat"] = msg["stat"]

            cpu["data"]._const["RTPWS"]["cid"] = msg["cid"]
            cpu["data"]._const["RTPWS"]["sid"] = msg["sid"]
            cpu["data"]._const["RTPWS"]["aip"] = msg["aip"]
            cpu["data"]._const["RTPWS"]["aport"] = msg["aport"]
            cpu["data"]._const["RTPWS"]["stat"] = msg["stat"]

    except Exception,e:
        log.error(str(e))

# 退出语音频道（组）：8004
def fnTcp_outChannelHandler(cpu,msg):
    try:
        if msg["err"] == 0:
            cpu["data"]._const["WS"]["stat"] = msg["stat"]
    except Exception,e:
        log.error(str(e))

# 音视频单呼：8007
def fnTcp_videoSingleCallHandler(cpu,msg):
    try:
        if msg["err"] == 0:
            cpu["data"]._const["WS"]["stat"] = msg["stat"]
    except Exception,e:
        log.error(str(e))

# 音视频组呼：8009
def fnTcp_videoGroupCallHandler(cpu,msg):
    log.info("start to handle the videoGroupCall data!")
    pass

# 呼叫结束：8011
def fnTcp_videoCallHangUpHandler(cpu,msg):
    log.info("start to handle the videoCallHangUp data!")
    pass

# 广播：8016
def fnTcp_boardcastHandler(cpu,msg):
    log.info("start to handle the boardcast data!")
    pass

# 广播结束：8018
def fnTcp_boardcastHangUpHandler(cpu,msg):
    log.info("start to handle the boardcastHangUp data!")
    pass

# 临时组对讲：8020
def fnTcp_temporaryTalkHandler(cpu,msg):
    log.info("start to handle the temporaryTalk data!")
    pass

# 临时组对讲结束：8022
def fnTcp_temporaryTalkHangUpHandler(cpu,msg):
    log.info("start to handle the temporaryTalkHangUp data!")
    pass

# 单呼结束：8005
def fnTcp_videoSingleCallHangUpHandler(cpu,msg):
    try:
        if msg["err"] == 0:
            cpu["data"]._const["WS"]["stat"] = msg["stat"]
    except Exception,e:
        log.error(str(e))

# 客户端上线
def fnTcp_clientOnlineHandler(cpu,msg):
    log.info("WS   Note:  uid ["+str(msg["uid"])+"] Online!")

# 客户端下线
def fnTcp_clientOutlineHandler(cpu,msg):
    log.info("WS   Note:  uid ["+str(msg["uid"])+"] Outline!")

# 加入群组
def fnTcp_clientJoinGroupHandler(cpu,msg):
    if msg["type"] == 1:
        log.info("WS   Note:  uid ["+str(msg["uid"])+"] join intercom, groupId is "+str(msg["gid"])+"!")
    elif msg["type"] == 2:
        log.info("WS   Note:  uid [" + str(msg["uid"]) + "] join meeting, groupId is " + str(msg["gid"]) + "!")
    elif msg["type"] == 3:
        log.info("WS   Note:  uid [" + str(msg["uid"]) + "] join broadcast, groupId is " + str(msg["gid"]) + "!")
    elif msg["type"] == 4:
        log.info("WS   Note:  uid [" + str(msg["uid"]) + "] join singleCall, groupId is " + str(msg["gid"]) + "!")
    elif msg["type"] == 5:
        log.info("WS   Note:  uid [" + str(msg["uid"]) + "] join tempGroup, groupId is " + str(msg["gid"]) + "!")
    else:
        log.info("WS   Note:  uid [" + str(msg["uid"]) + "] join intercom, groupId is " + str(msg["gid"]) + "!")



######################################
########### MSG 数据封装 Start #########
######################################
def getAccessRtpMsg(cid, sid, uid, destip, destport, payloadtype, sendflag):
    if(sid and cid):
        return {
            "cmd": 1,
            "sid": sid,
            "cid": cid,
            "uid": uid,
            "destip": destip,
            "destport": destport,
            "payloadtype": payloadtype,
            "sendflag": sendflag
        }

def getSendRtpMsg(sid, cid, sendflag):
    if (sid and cid):
        return {
            "cmd": 3,
            "sid": sid,
            "cid": cid,
            "sendflag": sendflag
        }

def getStopRtpMsg(sid, cid):
    if(sid and cid):
        return {
            "cmd": 2,
            "sid": sid,
            "cid": cid
        }

def getOtherMsg(self):
    log.info("=========== getOtherMsg() ==========")


# ********************
# 语音插件收发数据的处理
# ********************
def fnRtp_accessHandler():
    log.info("RTP  Note:  Start the rtp service!")

def fnRtp_stopRtpHandler():
    log.info("RTP  Note:  Stop the rtp service!")

def fnRtp_sendRtpHandler(cpu,msg):
    if msg["sendflag"] == 1:
        log.info("RTP  Note:  Start send voice!")
    else:
        log.info("RTP  Note:  Stop send voice!")

def fnRtp_recvPttHandler(cpu,msg):
    pass

def fnRtp_otherHandler(cpu,msg):
    pass